package team.yg.asset.service.impl;

import ch.qos.logback.classic.spi.EventArgUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import team.yg.asset.constant.CommonConstant;
import team.yg.asset.pojo.User;
import team.yg.asset.dao.UserMapper;
import team.yg.asset.properties.JwtProperties;
import team.yg.asset.resful.Result;
import team.yg.asset.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import team.yg.asset.utils.JWTUtil;
import team.yg.asset.vo.UserLoginVo;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Eins
 * @since 2024-10-03
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    JwtProperties jwt;

    @Override
    public User queryRoot() {
        User user = userMapper.selectById(1);
        return user;
    }

    /**
     * 登录功能
     * @param username,password
     * @return result
     * */
    @Override
    public Result<UserLoginVo> login(String username, String password) {
        // 1.根据用户名和密码查询用户是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.ge(User::getUsername,username).ge(User::getPassword,password);
        User user = userMapper.selectOne(wrapper);
        log.info("查询到的用户：{}",user);
        // 2.判断用户是否存在，不存在，返回登录失败
        if (user == null){
            return Result.error(CommonConstant.LOGIN_USER_ERROR);
        }
        // 3.存在,生成token
        // 3.1 将id和username封装到claims中
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("username", user.getUsername());
        //3.2 生成jwt令牌
        String jwtToken = JWTUtil.createJWT(jwt.getSecretKey(), jwt.getTtl(), claims);
        log.info("生成的token：{}",jwtToken);

        //4.将基本信息封装到vo对象里
        UserLoginVo userLoginVo = BeanUtil.copyProperties(user, UserLoginVo.class);
        userLoginVo.setToken(jwtToken);

        return Result.success(userLoginVo,CommonConstant.LOGIN_SUCCESS);
    }
}
